package yx.action.interceptot;

import java.util.Map;

import org.apache.struts2.ServletActionContext;

import yx.action.LoginAction;
import yx.vo.JsonVO;
import yx.vo.UserVO;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

    /**
     * 
     */
    private static final long serialVersionUID = 2495309798876116428L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        // 取得请求相关的ActionContext实例
        ActionContext ctx = invocation.getInvocationContext();
        @SuppressWarnings("rawtypes")
        Map session = ctx.getSession();
        Object login_o = session.get("LOGIN_USER");
        if(login_o instanceof UserVO){
            return invocation.invoke();
        }else if(invocation.getAction() instanceof LoginAction){
            return invocation.invoke();
        }else{
            JsonVO j = new JsonVO();
            j.setMsg("session会话已失效，请重新登录！");
            j.setSuccess(false);
            String json = JSON.toJSONStringWithDateFormat(j, "yyyy-MM-dd HH:mm:ss");
            ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
            ServletActionContext.getResponse().getWriter().write(json);
            ServletActionContext.getResponse().getWriter().flush();
            ServletActionContext.getResponse().getWriter().close();
            return null ;
        }
    }

}
